//
//  LauOAuthViewController.swift
//  SwiftProject
//
//  Created by Lausen on 2017/8/3.
//  Copyright © 2017年 id. All rights reserved.
//

import UIKit
import SVProgressHUD

class LauOAuthViewController: UIViewController {

    //懒加载一个网页视图
    private lazy var webView = UIWebView()
    
    override func loadView() {
        
        //加载视图的时候,更换当前控制器的跟视图
        view = webView
        
        webView.backgroundColor = UIColor.white
        
        //让webView 不滚动
        webView.scrollView.isScrollEnabled = false
        
        title = "登录"
        
        /// 设置左边的item
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", target: self, action: #selector(exit), isBack: true)
        
        /// 设置右边的item
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动登录", target: self, action: #selector(autoFill))
        
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(LauAppKey)&redirect_uri=\(LauRedirectURI)"
        
        guard let url = URL(string: urlString)else{
            return
        }
        
        let request = URLRequest(url: url)
        
        webView.loadRequest(request)
    }

//    左边item的点击事件
    @objc fileprivate func exit(){
        
        SVProgressHUD.dismiss()
        
        dismiss(animated: true, completion: nil)
    }
    
    @objc private func autoFill(){
        
        //1:准备js代码
        let jsCode = "document.getElementById('userId').value = '735414313@qq.com';" +
                    "document.getElementById('passwd').value = '18949933685liu';"
        
        //2:让WebView执行js代码 有叫做webView的注入
        webView.stringByEvaluatingJavaScript(from: jsCode)
    }
}

// MARK: - webView的代理方法
extension LauOAuthViewController: UIWebViewDelegate{
    
    //MARK: -- webView将要加载时调用的方法
    /// webView的代理方法
    ///
    /// - Parameters:
    ///   - webView: 当前的webView
    ///   - request: webView的请求
    ///   - navigationType: 请求的方式
    /// - Returns: 返回值
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
    
        //1:获取请求回来的连接
        
        
        //2:如果返回的连接的字符串中,包含了code就说明请求成功了,否则就是失败了
//        http://www.9caitong.com/?error_uri=%2Foauth2%2Fauthorize&error=access_denied&error_description=user%20denied%20your%20request.&error_code=21330 --------这个是点击取消的返回连接
        //Optional(http://www.9caitong.com/?code=54301f11fd982fecef02566979525843)这个是点击授权返回的连接\
        /*
         如果头部没有包含重定向地址,
         */
        if request.url?.absoluteString.hasPrefix(LauRedirectURI) == false {
            
            return true
        }
        
        //3如果取消授权
        if request.url?.absoluteURL.query?.hasPrefix("code=") == false {
            
            exit() //直接退出,
            
            return false //不加载
        }
        
        //4:走到这儿以后,code一定有值了,,获取code
        let code = request.url?.absoluteURL.query?.substring(from: "code=".endIndex) ?? ""
        
        print("授权码= == \(code)")
        
        LauNetworkManager.shared.loadAccessToken(code: code) { (isSuccess) in
            
            if !isSuccess{
                
                SVProgressHUD.showInfo(withStatus: "网络请求失败")
                
            }else{
                
                //1:提示框
                SVProgressHUD.showInfo(withStatus: "用户登录成功")
                
                //2:发送通知,刷新之前的界面
                NotificationCenter.default.post(
                    name: NSNotification.Name(rawValue: LauUserLoginSuccessNotification),
                    object: nil)
                
                //3:dismiss当前的控制器
                self.exit()
            }
        }
        //授权成功了不加载重定向地址的网页
        return false
    }
    
    //MARK: -- webView开始加载的方法
    func webViewDidStartLoad(_ webView: UIWebView) {
        
        SVProgressHUD.show()
    }
    
    //MARK: -- webView加载结束时调用的方法
    func webViewDidFinishLoad(_ webView: UIWebView) {
     
        SVProgressHUD.dismiss()
    }
    
}






















